/*
 * Created on 30-ene-2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.juanfrivaldes.cio2005.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.dao.DataAccessException;

import com.juanfrivaldes.cio2005.domain.Usuario;

/**
 * @author root
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class AutentificacionUsuarioAction extends BaseAction {

	private static Log log = LogFactory
			.getLog(AutentificacionUsuarioAction.class);

	protected ActionForward performAutentification(ActionMapping mapping,
			HttpServletRequest request, String email, String password) throws DataAccessException{
		
		Usuario usr = this.getCio2005().getUsuario(email, password);
		if (usr == null) {
			ActionMessages errors = new ActionErrors();
			errors.add("password", new ActionMessage(
					"accesoUsuario.user.problema"));
			log
					.trace("Usuario" + email + " " + password
							+ " acceso invalido\n");
			this.saveErrors(request, errors);

			return new ActionForward(mapping.getInput());
		}

		log.trace("Acceso de" + usr.getEmail() + usr.getApellidos()
				+ usr.getNombre() + usr.getPassword());

		// añadimos el nuevo usuario a la sesion
		request.getSession().setAttribute("currentUser", usr);

		return null;
	}

	protected ActionForward protectedExecute(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (isCancelled(request)) {
			return mapping.findForward("inicio");
		}

		AutentificacionUsuarioForm authForm = (AutentificacionUsuarioForm) form;

		try {

			request.setAttribute("destino", authForm.getDestino());

			ActionForward aForward = this.performAutentification(mapping,
					request, authForm.getEmail(), authForm.getPassword());

			// limpiamos el formulario
			authForm.setPassword("");
			authForm.setEmail("");
			
			if (aForward!=null)
				return aForward;

		} catch (Exception e) {
			log.trace("fallo en la base de datos");
			return mapping.findForward("dataFailure");
		}

		log.trace("Vamos a enviar al usuario autentificado a "
				+ authForm.getDestino());
		return mapping.findForward(authForm.getDestino());

	}
}
